import request, { ApiResponse } from './request'

// 备份信息
export interface BackupData {
  id: string
  filename: string
  filepath: string
  size: number
  description?: string
  created_at: string
}

// 创建备份参数
export interface CreateBackupParams {
  description?: string
}

// 删除备份参数
export interface DeleteBackupParams {
  id: string
}

// 删除备份响应
export interface DeleteBackupResponse {
  message: string
}

// 备份列表查询参数
export interface BackupListParams {
  page?: number
  pageSize?: number
}

// 备份列表响应
export interface BackupListResponse {
  list: BackupData[]
  total: number
  page: number
  pageSize: number
}

// 创建备份
export const createBackup = (data?: CreateBackupParams): Promise<ApiResponse<BackupData>> => {
  return request.post<BackupData>('/backups/create', data || {})
}

// 删除备份
export const deleteBackup = (data: DeleteBackupParams): Promise<ApiResponse<DeleteBackupResponse>> => {
  return request.post<DeleteBackupResponse>('/backups/delete', data)
}

// 获取备份列表
export const getBackupList = (data?: BackupListParams): Promise<ApiResponse<BackupListResponse>> => {
  return request.post<BackupListResponse>('/backups/list', data || {})
}

// 下载备份参数
export interface DownloadBackupParams {
  id: string
}

// 下载备份（返回 blob）
export const downloadBackup = async (data: DownloadBackupParams): Promise<Blob> => {
  // 直接使用 axios 创建请求，因为需要处理 blob 响应
  const axios = (await import('axios')).default
  const token = localStorage.getItem('portal-admin-token')
  const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
  
  try {
    const response = await axios.post(
      `${baseURL}/backups/download`,
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        responseType: 'blob',
        timeout: 60000 // 下载文件可能需要更长时间，设置为60秒
      }
    )
    
    // 检查响应是否为错误（blob 响应中，错误信息可能是 JSON 格式的 blob）
    if (response.data.type === 'application/json') {
      const text = await response.data.text()
      const errorData = JSON.parse(text)
      throw new Error(errorData.message || '下载失败')
    }
    
    return response.data
  } catch (error: any) {
    // 如果是 blob 类型的错误响应，尝试解析错误信息
    if (error.response?.data instanceof Blob && error.response.data.type === 'application/json') {
      const text = await error.response.data.text()
      const errorData = JSON.parse(text)
      throw new Error(errorData.message || '下载失败')
    }
    throw error
  }
}

